import 'package:OASys/api/MatterApi.dart';
import 'package:OASys/components/FormComponents.dart';
import 'package:OASys/entity/MatterVo.dart';
import 'package:OASys/utils/strUtils.dart';
import 'package:OASys/views/icon/myIcons.dart';
import 'package:flutter/material.dart';

class MyMatter extends StatefulWidget {
  final int status;

  MyMatter(this.status, {Key key});
  @override
  _MyMatterState createState() => _MyMatterState();
}

class _MyMatterState extends State<MyMatter>
    with SingleTickerProviderStateMixin {
  double _addPadding = 30;
  double _queryPadding = 30;
  bool flag = false;
  IconData actionIcon = MyIcons.spread;
  String loadText = "加载更多";
  MatterVo andQuery = new MatterVo();
  List<MatterVo> matterVoList = [];
  AnimationController _controller;
  int page = 1;
  int limit = 10;
  int total = 0;

  @override
  void initState() {
    super.initState();
    print(widget.status);
    andQuery.status = widget.status;
    getList();
    _controller =
        AnimationController(vsync: this, duration: Duration(milliseconds: 500))
          ..addListener(() {
            setState(() {
              _addPadding = 30 + 100 * _controller.value;
              _queryPadding = 30 + 200 * _controller.value;
            });
          });
  }

  void getList() {
    MatterApi().list(
      page,
      limit,
      andQuery: andQuery,
      success: (res) {
        setState(() {
          if (res.length > 0) {
            matterVoList = [];
            matterVoList.insertAll(total, res);
            total += res.length;
            page++;
          }
        });
        matterVoList.forEach((element) {
          print(element.toJson());
        });
      },
      error: (err) {
        print(err.code);
        showFailMessage(context);
      },
    );
  }

  void updateData() {
    setState(() {
      resetQueryData();
      getList();
    });
  }

  void resetQueryData() {
    setState(() {
      matterVoList = [];
      loadText = "加载更多";
      page = 1;
      limit = 10;
      total = 0;
    });
  }

  //跳转编辑
  Future toEdit(MatterVo item, bool isEdit) async {
    Navigator.of(context, rootNavigator: true).pop();
    var result = await Navigator.of(context).pushNamed(
      '/matterEdit',
      arguments: {
        'info': item.toJson(),
        'isEdit': isEdit,
      },
    );
    if (result == null || !result) {
      print('未编辑成功');
    } else {
      updateData();
      print('编辑成功');
    }
  }

  //跳转添加
  Future<void> toAdd() async {
    var result =
        await Navigator.of(context).pushNamed('/matterEdit', arguments: {
      'info': {
        'id': -1,
      },
      'isEdit': true
    });
    if (result == null || !result) {
      print('未添加成功');
    } else {
      updateData();
      print('添加成功');
    }
  }

  void remove(MatterVo item) {
    MatterApi().remove(
      item.id,
      success: (res) {
        Navigator.of(context, rootNavigator: true).pop();
        showSuccessMessage(context);
        updateData();
      },
      error: (err) {
        showMessage(context, err.message);
      },
    );
  }

  // 改变状态
  setStatus(MatterVo item, int status) {
    MatterApi().setStatus(
      item.id,
      status,
      success: (res) {
        Navigator.of(context, rootNavigator: true).pop();
        showSuccessMessage(context);
        updateData();
      },
      error: (err) {
        print(err.code);
        showFailMessage(context);
      },
    );
  }

  onClick(MatterVo item) {
    showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          titlePadding: EdgeInsets.all(0),
          title: Container(
            height: 50,
            alignment: Alignment.center,
            child: Text(
              '通知公告信息',
              style: TextStyle(color: Colors.white),
            ),
            decoration: BoxDecoration(
              color: Colors.blue,
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(3),
                topRight: Radius.circular(3),
              ),
            ),
          ),
          contentPadding: EdgeInsets.all(0),
          content: Container(
            height: 300,
            width: 300,
            decoration: BoxDecoration(
              color: Color.fromRGBO(250, 250, 250, 1),
              borderRadius: BorderRadius.circular(10),
            ),
            child: Container(
              margin: EdgeInsets.only(
                top: 20,
                bottom: 20,
              ),
              height: 260,
              child: SingleChildScrollView(
                scrollDirection: Axis.vertical,
                child: Column(
                  children: [
                    InfoItem('事项名称',
                        StrUtils.isNotBlank(item.name) ? item.name : "无"),
                    InfoItem('事项状态', item.statusName),
                    InfoItem('截止时间', item.deadline),
                    InfoItem(
                        '完成时间',
                        StrUtils.isNotBlank(item.completeTime)
                            ? item.completeTime
                            : "尚未完成"),
                    InfoItem('创建时间', item.createTime),
                  ],
                ),
              ),
            ),
          ),
          actions: <Widget>[
            Visibility(
              visible: item.status == 0,
              child: RaisedButton(
                color: Colors.yellow,
                child: Text(
                  '完 成',
                  style: TextStyle(color: Colors.white),
                ),
                onPressed: () {
                  setStatus(item, 1);
                },
              ),
            ),
            Visibility(
              visible: item.status == 1,
              child: RaisedButton(
                color: Colors.redAccent,
                child: Text(
                  '撤 回',
                  style: TextStyle(color: Colors.white),
                ),
                onPressed: () {
                  setStatus(item, 0);
                },
              ),
            ),
            Visibility(
              visible: item.status == 0,
              child: RaisedButton(
                color: Color.fromRGBO(33, 150, 243, 1),
                child: Text('修 改'),
                onPressed: () {
                  toEdit(item, true);
                },
              ),
            ),
            RaisedButton(
              color: Color.fromRGBO(103, 194, 58, 1),
              child: Text(
                '查 看',
                style: TextStyle(color: Colors.white),
              ),
              onPressed: () {
                toEdit(item, false);
              },
            ),
            RaisedButton(
              color: Color.fromRGBO(245, 108, 108, 1),
              child: Text('删 除'),
              onPressed: () {
                remove(item);
              },
            ),
          ],
        );
      },
    );
  }

  /// 构建卡片
  Widget buildListItem(int index) {
    return FlatButton(
      child: Card(
        child: Container(
          width: 800,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              ItemTitle(matterVoList[index].name),
              ItemContext(
                  '状态：',
                  StrUtils.isNotBlank(matterVoList[index].statusName)
                      ? matterVoList[index].statusName
                      : '无'),
              ItemContext(
                  '截止时间：',
                  StrUtils.isNotBlank(matterVoList[index].deadline)
                      ? matterVoList[index].deadline
                      : '尚未发布'),
              ItemContext('创建时间：', matterVoList[index].createTime),
            ],
          ),
        ),
      ),
      onPressed: () {
        onClick(matterVoList[index]);
      },
    );
  }

  /// 按钮收缩展开
  shrinkage() {
    setState(() {
      flag = !flag;
      if (flag) {
        actionIcon = MyIcons.shrink;
        _controller.forward();
      } else {
        actionIcon = MyIcons.spread;
        _controller.reverse();
      }
    });
  }

  // 加载更多
  void doLoad() {
    MatterApi().list(
      page,
      limit,
      andQuery: andQuery,
      success: (res) {
        if (res == null || res.length == 0) {
          print('无数据');
          setState(() {
            loadText = "没有更多了";
          });
          return;
        }
        setState(() {
          matterVoList.addAll(res);
          total += res.length;
          page++;
          loadText = "加载更多";
        });
        matterVoList.forEach((element) {
          print(element.toJson());
        });
      },
      error: (err) {
        print(err.code);
        print(err.message);
        showMessage(context, err.message);
      },
    );
  }

  Widget buildLoadMore() {
    return FlatButton(
      child: Container(
        child: Text(
          loadText,
          style: TextStyle(color: Colors.blue, fontSize: 12),
        ),
      ),
      onPressed: () {
        doLoad();
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Container(
          padding: EdgeInsets.only(top: 10, bottom: 10),
          height: 720,
          child: ListView.builder(
            itemCount: total + 1,
            itemBuilder: (BuildContext context, int index) {
              if (index == total) {
                return buildLoadMore();
              }
              return buildListItem(index);
            },
          ),
        ),
        Positioned(
          right: _queryPadding,
          bottom: 30,
          child: Container(
            width: 68,
            height: 68,
            child: RaisedButton(
              color: Colors.yellow,
              child: Icon(
                MyIcons.query,
                color: Colors.white,
                size: 30,
              ),
              shape: CircleBorder(),
              onPressed: () {
                print('查询');
              },
            ),
          ),
        ),
        Positioned(
          right: _addPadding,
          bottom: 30,
          child: Container(
            width: 68,
            height: 68,
            child: RaisedButton(
              color: Colors.green,
              child: Icon(
                MyIcons.add,
                color: Colors.white,
                size: 30,
              ),
              shape: CircleBorder(),
              onPressed: () {
                toAdd();
              },
            ),
          ),
        ),
        Positioned(
          right: 30,
          bottom: 30,
          child: Container(
            width: 68,
            height: 68,
            child: RaisedButton(
              color: Colors.blue,
              child: Icon(
                actionIcon,
                color: Colors.white,
                size: 30,
              ),
              shape: CircleBorder(),
              onPressed: shrinkage,
            ),
          ),
        ),
      ],
    );
  }
}
